<?php

function compare_workload_periods($a, $b){
    if ($a['amount'] == $b['amount']) {
        if(strtotime($a['startDate']) < strtotime($b['startDate']))
            return -1;
        return 0;
    }
    return ($a['amount'] < $b['amount']) ? -1 : 1;
}
function only_predicted($time_groups, $amount_key){
    $predictions = Array();
    foreach($time_groups as $record){
        foreach($record as $date => $amounts){
            if($amounts->predicted){
                $predictions[] = Array('date' => $date, 'amount' => $amounts->$amount_key);
            }
        }
    }
    return $predictions;
}

require 'DB/db_data_loader.php';
require 'Processing/Subdivisions/subdivision_data_processing.php';

//Bendri duomenys tiek padaliniams tiek IS
$measures = get_support_measures_associative(); //Surenka paraiškos priemonių kodus ir pavadinimus
$dates = SubdivisionData::get_dates_predicted(12);
    
if(isset($_POST['selectedSubdivision']) && $_POST['selectedSubdivision'] != ''){
    $dataset = SubdivisionData::counts_to_dataset_for_subdivision($_POST['selectedSubdivision']); //Surenka istorinius duomenis apie gautas paraiškas
    $subdivisions = get_subdivision_by_code($_POST['selectedSubdivision']);
    if(empty($subdivisions)){
        die("alert('Klaida: neatpažintas padalinys. Pabandykite iš naujo nustatyti filtro parametrus.')");
    }
    $time_groups = SubdivisionData::dataset_to_table($dataset, $subdivisions, $dates, $is_time_groups, SubdivisionData::get_measures_subdivisions_by_subdivision_code($_POST['selectedSubdivision']));
    SubdivisionData::predict($time_groups);
    //$amount_key = 'predicted_received';
    $amount_key = 'predicted_time';
}
elseif(isset($_POST['selectedIS']) && $_POST['selectedIS'] != ''){
    require 'Processing/InformationSystems/is_data_processing.php';
    $dataset = SubdivisionData::counts_to_dataset(); //Surenka istorinius duomenis apie gautas paraiškas
    $subdivisions = get_subdivisions_associative();
    $is = get_is_by_code($_POST['selectedIS']);
    if(empty($is)){
        die("alert('Klaida: neatpažinta informacinė sistema. Pabandykite iš naujo nustatyti filtro parametrus.')");
    }
    $time_groups = SubdivisionData::dataset_to_table($dataset, $subdivisions, $dates, $is_time_groups);
    $filtered_is_timegroups = Array($_POST['selectedIS'] => $is_time_groups[$_POST['selectedIS']]);
    ISData::predict_is($filtered_is_timegroups);
    //$amount_key = 'sum_n';
    $amount_key = 'sum_time';
    $time_groups = $filtered_is_timegroups;
}
else die('Neatpažinti parametrai');
//Leave only predicted data:
$predictions = only_predicted($time_groups, $amount_key);


if($_POST['timePeriod'] == -1){
    $workflow_periods = Array();
    for($i = 0; $i < count($predictions); $i++){
        preg_match("/(\d{4})-(\d{2})-(\d{2})/", $predictions[$i]['date'], $matches);
        if(2 < $matches[2] && $matches[2] < 11 && array_key_exists($i+1, $predictions)){
            $workflow_periods[] = Array(
                'startDate' => $predictions[$i]['date'], 
                'startMonthIndex' => $i,
                'endDate' => $predictions[$i+1]['date'],
                'endMonthIndex' => $i+1,
                'amount' => ($predictions[$i]['amount'] + $predictions[$i+1]['amount'])
            );
        }
        if($matches[2] == 12 && array_key_exists($i+2, $predictions)){
            $workflow_periods[] = Array(
                'startDate' => $predictions[$i]['date'], 
                'startMonthIndex' => $i,
                'endDate' => $predictions[$i+2]['date'],
                'endMonthIndex' => $i+2,
                'amount' => ($predictions[$i]['amount'] + $predictions[$i+1]['amount'] + $predictions[$i+2]['amount'])
            );
        }
    }  
} else {
    $months_number = ceil($_POST['timePeriod'] / 30);
    $workflow_periods = Array();
    for($i = 0; $i < (count($predictions)-$months_number+1); $i++){
        $sum_amount = 0;
        for($j = 0; $j < $months_number; $j++){
            $sum_amount += $predictions[$i+$j]['amount'];
        }
        $j--;
        $workflow_periods[] = Array(
            'startDate' => $predictions[$i]['date'],
            'startMonthIndex' => $i,
            'endDate' => $predictions[$i+$j]['date'],
            'endMonthIndex' => $i+$j,
            'amount' => $sum_amount
        );
    }
}
usort($workflow_periods, "compare_workload_periods");
//laikotarpių apjungimas
//TODO: apgalvoti dėl paraiškų kiekio pasikeitimo
/*for($i = 0; $i < (count($workflow_periods)-1); $i++){
    if($workflow_periods[$i]['amount'] == $workflow_periods[$i+1]['amount']){
        echo $i.' ';
        if(strtotime($workflow_periods[$i]['endDate']) >= strtotime($workflow_periods[$i+1]['startDate'])){
            echo 'laikai tiko';
            $sum_amount = 0;
            for($j = $workflow_periods[$i]['startMonthIndex']; $j <= $workflow_periods[$i+1]['endMonthIndex']; $j++){
                $sum_amount += $predictions[$j]['amount'];
            }
            $workflow_periods[$i]['amount'] = $sum_amount;
            $workflow_periods[$i]['endDate'] = $workflow_periods[$i+1]['endDate'];
            $workflow_periods[$i]['endMonthIndex'] = $workflow_periods[$i+1]['endMonthIndex'];
            $workflow_periods[$i+1]['inOtherPeriod'] = true;
        }
    }
}*/


$content = "appData = [";
foreach($workflow_periods as $key => $period){
    preg_match("/(\d{4})-(\d{2})-(\d{2})/", $period['endDate'], $endDate);
    $endDate[2]++;
    if($endDate[2] == 13){
        $endDate[2] = 1;
        $endDate[1]++;
    }
    $period['endDate'] = $endDate[1].'-'.str_pad($endDate[2], 2, "0", STR_PAD_LEFT).'-'.$endDate[3];
    $content .= "{ type: ".($key+1).", startDate: '".$period['startDate']."', endDate: '".$period['endDate']."', amount: ".$period['amount']."},";
}
$content = substr_replace($content, "}]", -2);
echo $content;
?>

